var win = Titanium.UI.currentWindow;
win.title='Setup';
win.backgroundColor='#fff';

var table = Titanium.UI.createTableView({deleteButtonTitle:'Delete'});
table.addEventListener('delete',function(e){
	db.execute("delete from POPBOXES where IP='"+escape(e.row.title)+"'");
});

var db = Titanium.Database.open('popboxes');
db.execute('CREATE TABLE IF NOT EXISTS POPBOXES  (IP STRING)');
db.execute('CREATE TABLE IF NOT EXISTS SETTINGS  (NAME STRING,VALUE STRING)');

fillBoxes();

function fillBoxes(){
	var data =[];
	var rows = db.execute('SELECT IP FROM POPBOXES');
	if(rows.rowCount==0){
		 addBoxDialog();
	}else{
		while (rows.isValidRow()){
			data.push({title:rows.field(0).toString()});
			rows.next();
		}
	}
	rows.close();
	table.setData(data);
}

win.barColor = '#000000';

var a = Titanium.UI.createButton({title:'Add'});
win.leftNavButton = a;
a.addEventListener('click', function(){addBoxDialog();});

var b = Titanium.UI.createButton({title:'Edit'});
win.rightNavButton = b;
b.addEventListener('click', function(){
	if(b.title=="Edit"){
		table.editing = true;
		b.title="Cancel"
	}else{
		table.editing = false;
		b.title="Edit"
	}
});

win.add(table);


function addBoxDialog(){
	var winaddPop=Ti.UI.createWindow({
		title:"Add a box",
		backgroundColor:'#000000'
		
	});
	var adBoxOk=Ti.UI.createButton({title:"OK",top:60,left:10,right:10,height:35});
	var adBoxCancel=Ti.UI.createButton({title:"Cancel",top:110,left:10,right:10,height:35});
	var txtIP=Ti.UI.createTextField({color:'#336699',hintText:"IP Address",height:35,top:10,left:10,right:10,borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED});    
	winaddPop.add(txtIP);
	winaddPop.add(adBoxOk);
	winaddPop.add(adBoxCancel);
	winaddPop.open({modal:true});
	txtIP.focus();
	adBoxCancel.addEventListener('click',function(e){winaddPop.close();});	
	adBoxOk.addEventListener('click',function(e){
	db.execute("INSERT INTO POPBOXES (IP) values('"+txtIP.value+"')");
   	 winaddPop.close();
   	 fillBoxes();
	});

}


table.addEventListener('click', function(e){
	Titanium.App.fireEvent("setTab",{tab:1,ip:e.row.title});
});